package cn.cyh.queue_service.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * 配置密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    /**
     * 配置安全过滤器链
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF保护
            .csrf(AbstractHttpConfigurer::disable)
            // 禁用HTTP基本认证
            .httpBasic(AbstractHttpConfigurer::disable)
            // 无状态会话管理
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            // 异常处理
            .exceptionHandling(exception -> exception
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)
            )
            // 请求授权
            .authorizeHttpRequests(auth -> auth
                // 允许访问公共资源
                .requestMatchers("/auth/login", "/auth/register").permitAll()
                .requestMatchers("/face/**").permitAll()
                .requestMatchers("/queue/customer/**").permitAll()
                .requestMatchers("/service-types", "/service-types/active").permitAll()
                .requestMatchers("/queue/status").permitAll()
                .requestMatchers("/queue/screens/**").permitAll()
                .requestMatchers("/notice/**").permitAll().requestMatchers("/callScreen/**").permitAll()
                // 统计相关API - 确保与前端调用路径完全匹配
                .requestMatchers("/statistics/today").permitAll()
                .requestMatchers("/statistics/current").permitAll()
                .requestMatchers("/statistics/daily").permitAll()
                .requestMatchers("/statistics/by-window").permitAll()
                .requestMatchers("/statistics/by-business-type").permitAll()
                .requestMatchers("/statistics/weekly").permitAll()
                .requestMatchers("/statistics/range").permitAll()
                .requestMatchers("/statistics/export").permitAll()
                
                // 窗口管理相关API
                .requestMatchers("/windows/**").permitAll()
                 // 抢票相关
                .requestMatchers("/queue/**").permitAll()
                
                // WebSocket相关
                .requestMatchers("/ws/**").permitAll()
                
                // Swagger和健康检查
                .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
                
                // 调试时临时允许所有请求(开发阶段)
                .anyRequest().permitAll()
                // 生产环境使用下面的配置
//                 .anyRequest().authenticated()
            )
            // 添加JWT过滤器
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
} 